home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!pbutler.demon.co.uk
- From: Peter Hugh Butler <Peter@pbutler.demon.co.uk>
- Newsgroups: comp.lang.c++
- Subject: "Deep" Destructor Query
- Date: Fri, 08 Mar 96 03:53:00 GMT
- Organization: Myorganisation
- Message-ID: <826257180snz@pbutler.demon.co.uk>
- Reply-To: Peter@pbutler.demon.co.uk
- X-NNTP-Posting-Host: pbutler.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.30
- X-Mail2News-Path: pbutler.demon.co.uk
-
- I have two questions, hope nobody minds. Please answer by e-mail, unless
- you think that the group would benefit from the answer.
-
- I have read the FAQ on this subject, but I am still a little confused.
- (By the way, I know I should use a dynamic multi-dimensional array, but I
- just wanted to try it this way).
-
- Destructors
-
- I have two classes, one instantiated in the other. One (shape) contains a
- dynamic array of structs, the other (object) contains a dynamic array of
- shapes. Declared sort of like this:
-
- struct point
- {
- int x, y, z;
- };
-
- Class Shape
- {
- private:
- point *p; //dynamic array of points
- //...etc
- };
-
- Class Object
- {
- private:
- int numshapes; //number of data elements
- shape *shapes; //dynamic array of shapes
- //etc...
- };
-
- Now, this all works quite well, apart from when it comes to destructor
- functions. For shape I have:
-
- Shape::~Shape()
- {
- if (p)
- delete [] p;
- }
-
- which works ok. But when I wrote a destructor for Object, like this:
-
- Object::~Object()
- {
- for (int i = 0; i < numshapes; i++)
- shapes[i].~shape(); //"Deep" destructor, deletes underlying arrays.
-
- delete [] shapes; //delete the array of pointers
- }
-
- The program causes a General Protection Fault (guess which OS I'm using and
- win a cookie). It fails when it tries to delete the array of null pointers
- pointed to by shape. It works when I leave the "delete [] shapes;" line out.
-
- Well, I have two questions:
-
- 1) If I simply "delete [] shapes" with no loop to delete the arrays underneath,
- will the ~shape() destructor be automatically called, thus deleting the
- shape objects correctly? I wouldn't think so, but it would be good to be
- corrected.
-
- 2) If I delete each shape with a loop (as above), does this mean that shapes
- pointer points to nothing? I would have thought that it would point to
- an array of null pointers.
-
- Thanks for any comments/opinions/advice.
-
- --
- Peter Hugh Butler
-